package com.example.webtest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {


    private Button btn_send;
    private Button back;
    private long exitTime = 0;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exit();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        finish();
    }

    String url = "https://wanandroid.com/user/login";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button login = findViewById(R.id.login);
        login.setOnClickListener(new LoginActivity());
        Button resiger = findViewById(R.id.resiger);
        resiger.setOnClickListener(new ResigerActivity());
        back = (Button) findViewById(R.id.button4);
        back.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示")
                        .setMessage("是否确定要退出")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog,int which){
                                finish(); }})
                        .setNegativeButton("取消",null)
                        .show();

            }
        });
    }
    class ResigerActivity implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,Resiger.class);
            startActivity(intent);
        }
    }
    class LoginActivity implements View.OnClickListener{
        int result = 1;
        @Override
        public void onClick(View v) {
            new Thread(){
                public void run(){
                    String username = ((EditText)findViewById(R.id.username)).getText().toString();
                    String password = ((EditText)findViewById(R.id.password)).getText().toString();
                    result = login(url,username,password);
                }
            }.start();
            if (result == 1){
                Toast.makeText(MainActivity.this, "账号密码不匹配！", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private int login(String url, String username, String password) {
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(5000);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            String data = "username=" + URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();
            if (urlConnection.getResponseCode() == 200){
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                while((line = bufferedReader.readLine()) != null){
                    stringBuffer.append(line);
                }
                System.out.println(stringBuffer.toString());
                String string = stringBuffer.toString();
                JSONObject jsonObject = new JSONObject(string);
                String errorMsg = jsonObject.optString("errorCode");
                if (errorMsg.equals("0")){
                    Uri uri = Uri.parse("https://wanandroid.com/index");
                    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                    startActivity(intent);
                    return 0;
                }
                return 1;
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return 1;
    }
}